package cn.edu.zafu.bigdata.weier;

import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(1234);
            System.out.println("Server is running and waiting for client connection...");

            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Client connected.");

                BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter output = new PrintWriter(socket.getOutputStream(), true);

                String clientMessage;
                while ((clientMessage = input.readLine()) != null) {
                    System.out.println("Client says: " + clientMessage);

                    // Echo back the received message
                    output.println("Server received: " + clientMessage);

                    // Optional: Close the connection if a specific message is received
                    if ("bye".equalsIgnoreCase(clientMessage)) {
                        System.out.println("Client disconnected.");
                        break;
                    }
                }

                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}